package com.lee.dutylower.view.detail;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.lee.dutylower.MyApplication;
import com.lee.dutylower.R;
import com.lee.dutylower.db.greenEntity.Sentry;
import com.lee.dutylower.db.greenEntity.Soldier;
import com.lee.dutylower.db.greenEntity.Squad;
import com.lee.dutylower.db.greendao.SentryDao;
import com.lee.dutylower.db.greendao.SquadDao;
import com.lee.dutylower.utils.Globals;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class SoldierDetailFragment extends Fragment {
    public EditText etName;
    public LinkedList<Long> sentryGroup;
    //判断当前是否为正在添加新数据
    public boolean isAdd = false;
    public long squadID = -1;
    public int grade = -1;

    private Spinner spSquad;
    private TextView tvSentrys;
    private TextView tvCurrentSquad;

    private RadioGroup radioGroup;

    private Soldier soldierDB;

    private List<String> sentrys;

    private boolean isEditable = false;
    private SquadDao squadDao;
    private SentryDao sentryDao;
    private ListAdapter listAdpter;
    private AlertDialog alert;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            soldierDB = (Soldier) getArguments().getSerializable("soldier");
            isEditable = getArguments().getBoolean("isEditable",false);
        }
        sentrys = new ArrayList<>();
        if(soldierDB != null){
            List<Sentry> sentries = soldierDB.getSentryGroup();
            for (Sentry sentry : sentries) {
                sentrys.add(sentry.getSentry_name());
            }
        }

        squadDao = MyApplication.getApplication().getDaoSession().getSquadDao();
        sentryDao = MyApplication.getApplication().getDaoSession().getSentryDao();
        Globals.ALLSquad = squadDao.queryBuilder().build().list();
        Globals.ALLSentry = sentryDao.queryBuilder().build().list();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_detail_soldier,null);
        etName = (EditText) view.findViewById(R.id.et_detail_name);
        spSquad = (Spinner) view.findViewById(R.id.sp_detail_squad);
        tvSentrys = (TextView) view.findViewById(R.id.tv_detail_sentry);
        tvCurrentSquad = (TextView) view.findViewById(R.id.tv_current_squad);
        radioGroup = (RadioGroup) view.findViewById(R.id.rg_detail_grade);
        if(soldierDB == null){
            initEditableView(null);
            editViewInit(false);
            isAdd = true;
        }else {
            isAdd = false;
            dataNotNull();
        }
        return view;
    }

    @NonNull
    public void dataNotNull() {

        if(isEditable){
            initEditableView(soldierDB.getSName());
        }else {
            etName.setEnabled(false);
            tvSentrys.setClickable(false);
            spSquad.setEnabled(false);
            for (int i = 0; i < radioGroup.getChildCount(); i++) {
                radioGroup.getChildAt(i).setClickable(false);
            }
            etName.setText(soldierDB.getSName());
        }
        editViewInit(true);
    }

    private void editViewInit(boolean notnull) {
        if (notnull){
            /**
             * 班级显示编辑
             */
            Squad s = squadDao.queryBuilder().where(SquadDao.Properties.SuqadId.eq(soldierDB.getSquadID())).build().unique();
            tvCurrentSquad.setText("当前班级："+s.getSquadName());
            final List<String> items = new ArrayList<>();
            for (Squad squadDB : Globals.ALLSquad) {
                items.add(squadDB.getSquadName());
            }
            ArrayAdapter<String> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_spinner_item,items);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spSquad.setAdapter(adapter);
            spSquad.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    for (Squad squadDB : Globals.ALLSquad) {
                        if (items.get(position).equals(squadDB.getSquadName())){
                            squadID = squadDB.getSuqadId();
                        }
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            /**
             * 哨位显示编辑
             */
            tvSentrys.setText(sentrys.toString());

            /**
             * 职务显示
             */
            int i = soldierDB.getGrade();
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    if (checkedId == R.id.rb_detail_monitor){
                        grade = 1;
                    }
                    if (checkedId == R.id.rb_detail_soldier){
                        grade = 0;
                    }
                }
            });
            RadioButton rb = (RadioButton) radioGroup.getChildAt(i);
            rb.setChecked(true);
        }else {
            /**
             * 班级显示编辑
             */
            tvCurrentSquad.setText("当前班级：无");
            final List<String> items = new ArrayList<>();
            for (Squad squadDB : Globals.ALLSquad) {
                items.add(squadDB.getSquadName());
            }
            ArrayAdapter<String> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_spinner_item,items);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spSquad.setAdapter(adapter);
            spSquad.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    for (Squad squadDB : Globals.ALLSquad) {
                        if (items.get(position).equals(squadDB.getSquadName())){
                            squadID = squadDB.getSuqadId();
                        }
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            /**
             * 哨位显示编辑
             */
            tvSentrys.setText("请选择哨位");

            /**
             * 职务显示
             */
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    if (checkedId == R.id.rb_detail_monitor){
                        grade = 1;
                    }
                    if (checkedId == R.id.rb_detail_soldier){
                        grade = 0;
                    }
                }
            });
        }
    }

    //当判断为可编辑的时候进行初始化
    public void initEditableView(String sname) {
        etName.setEnabled(true);
        tvSentrys.setClickable(true);
        spSquad.setEnabled(true);
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            radioGroup.getChildAt(i).setClickable(true);
        }
        if(sname != null){
            etName.setText(sname);
        }
        //点击展示哨位列表布局
        listAdpter =  new ListAdapter(Globals.ALLSentry);
        tvSentrys.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Globals.GUARDSentry.clear();
                alert = new AlertDialog.Builder(getActivity())
                        .setView(initDialogView())
                        .setCancelable(true)
                        .setTitle("全部哨位")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //每次确定后 进行界面数据的更新 此时并未入库
                                sentryGroup = new LinkedList<>();
                                sentrys.clear();
                                for (Sentry sentryDB : Globals.GUARDSentry) {
                                    sentryGroup.add(sentryDB.getSentry_id());
                                    sentrys.add(sentryDB.getSentry_name());
                                }
                                tvSentrys.setText(sentrys.toString());
                            }
                        })
                        .setNegativeButton("取消",null)
                        .create();
                alert.show();
            }
        });
    }

    @NonNull
    private View initDialogView() {
        final View dialogview = View.inflate(getActivity(), R.layout.dialog_setting_list,null);
        ListView listView = (ListView) dialogview.findViewById(R.id.lv_dialog);
        listView.setAdapter(listAdpter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView) view.findViewById(R.id.tv_lv_data);
                if(Globals.GUARDSentry.contains(Globals.ALLSentry.get(position))){
                    tv.setBackgroundColor(Color.TRANSPARENT);
                    Globals.GUARDSentry.remove(Globals.ALLSentry.get(position));
                }else {
                    tv.setBackgroundColor(0xFFA36F59);
                    Globals.GUARDSentry.add(Globals.ALLSentry.get(position));
                }
            }
        });
        return dialogview;
    }

    class ListAdapter extends BaseAdapter { private List values;
        public ListAdapter(List values) {
            this.values = values;
        }

        @Override
        public int getCount() {
            return values.size();
        }

        @Override
        public Object getItem(int position) {
            return values.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            Sentry sentry = (Sentry) values.get(position);
            if(convertView == null){
                holder = new ViewHolder();
                convertView = View.inflate(getActivity(),R.layout.dialog_listview_item,null);
                holder.tv = (TextView) convertView.findViewById(R.id.tv_lv_data);
                holder.ID = (TextView) convertView.findViewById(R.id.tv_lv_id);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.tv.setText(sentry.getSentry_name());
            holder.ID.setText(sentry.getSentry_id()+"");
            return convertView;
        }

        class ViewHolder{
            TextView tv;
            TextView ID;
        }
    }
}
